package edu.arhs.team1100.gamename.forms;

import edu.arhs.team1100.gamename.handlers.EventHandler;
import edu.arhs.team1100.gamename.handlers.TeamEventMatchHandler;
import edu.arhs.team1100.gamename.handlers.TeamHandler;
import edu.arhs.team1100.gamename.objects.Team;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Eddie
 */
public class TeamViewPanel extends javax.swing.JPanel {

    public static final int SINGLE_SELECT = 1;
    public static final int MULTI_SELECT = 2;
    public static final int EDIT = 3;

    /**
     * Creates new form TeamSelectPanel
     *
     * @param teamsToView
     * @param option
     */
    public TeamViewPanel(List<Team> teamsToView, int option) {
        initComponents();
        loadTeams(teamsToView);
        
        if (option == EDIT || option == SINGLE_SELECT) {
            teamTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        }
        if (option == EDIT) {
            initRightMouseClick();
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        editPopupMenu = new javax.swing.JPopupMenu();
        editMenuItem = new javax.swing.JMenuItem();
        deleteMenuItem = new javax.swing.JMenuItem();
        jScrollPane1 = new javax.swing.JScrollPane();
        teamTable = new javax.swing.JTable();

        editMenuItem.setText("Edit");
        editMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editMenuItemActionPerformed(evt);
            }
        });
        editPopupMenu.add(editMenuItem);

        deleteMenuItem.setText("Delete");
        deleteMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteMenuItemActionPerformed(evt);
            }
        });
        editPopupMenu.add(deleteMenuItem);

        teamTable.setAutoCreateRowSorter(true);
        teamTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Team Number", "Name", "Location", ""
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        teamTable.getTableHeader().setReorderingAllowed(false);
        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment( JLabel.CENTER );
        teamTable.setDefaultRenderer(String.class, centerRenderer);
        teamTable.setDefaultRenderer(Integer.class, centerRenderer);
        jScrollPane1.setViewportView(teamTable);
        if (teamTable.getColumnModel().getColumnCount() > 0) {
            teamTable.getColumnModel().getColumn(0).setResizable(false);
            teamTable.getColumnModel().getColumn(1).setResizable(false);
            teamTable.getColumnModel().getColumn(2).setResizable(false);
            teamTable.getColumnModel().getColumn(3).setMinWidth(0);
            teamTable.getColumnModel().getColumn(3).setPreferredWidth(0);
            teamTable.getColumnModel().getColumn(3).setMaxWidth(0);
        }

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 482, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    private void editMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editMenuItemActionPerformed
        DefaultTableModel model = (DefaultTableModel) teamTable.getModel();
        TeamManualPanel teamPanel = new TeamManualPanel(getSingleTeam());
        int eventResult = JOptionPane.showConfirmDialog(this, teamPanel, "Edit Team", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

        if (eventResult == JOptionPane.OK_OPTION) {
            Team updatedTeam = teamPanel.getTeam();
            TeamHandler.updateTeam(updatedTeam);
            int position = teamTable.getSelectedRow();
            model.removeRow(position);
            model.insertRow(position, new Object[]{updatedTeam.getTeamNumber(), updatedTeam.getNickname(), updatedTeam.getLocation(), updatedTeam});
        }
    }//GEN-LAST:event_editMenuItemActionPerformed

    private void deleteMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteMenuItemActionPerformed
        DefaultTableModel model = (DefaultTableModel) teamTable.getModel();
        TeamHandler.deleteTeam(getSingleTeam());
        model.removeRow(teamTable.getSelectedRow());
    }//GEN-LAST:event_deleteMenuItemActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem deleteMenuItem;
    private javax.swing.JMenuItem editMenuItem;
    private javax.swing.JPopupMenu editPopupMenu;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable teamTable;
    // End of variables declaration//GEN-END:variables

    public List<Team> getMultipleTeams() {
        ArrayList<Team> selectedTeams = new ArrayList();
        for (int i = 0; i < teamTable.getSelectedRowCount(); i++) {
            selectedTeams.add((Team) teamTable.getValueAt(teamTable.getSelectedRows()[i], 3));
        }
        return selectedTeams;
    }

    public Team getSingleTeam() {
        if (teamTable.getSelectedRow() != -1) {
            return (Team) teamTable.getValueAt(teamTable.getSelectedRow(), 3);
        } else {
            return null;
        }
    }

    private void loadTeams(List<Team> teamsToView) {
        DefaultTableModel model = (DefaultTableModel) teamTable.getModel();
        for (Team team : teamsToView) {
            model.addRow(new Object[]{team.getTeamNumber(), team.getNickname(), team.getLocation(), team});
        }
    }

    private void initRightMouseClick() {
        teamTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                int r = teamTable.rowAtPoint(e.getPoint());
                if (r >= 0 && r < teamTable.getRowCount()) {
                    teamTable.setRowSelectionInterval(r, r);
                } else {
                    teamTable.clearSelection();
                }

                int rowindex = teamTable.getSelectedRow();
                if (rowindex < 0) {
                    return;
                }
                if (e.isPopupTrigger() && e.getComponent() instanceof JTable) {
                    editPopupMenu.show(e.getComponent(), e.getX(), e.getY());
                }
            }

            @Override
            public void mousePressed(MouseEvent me) {
                if (me.getClickCount() == 2) {
                    editMenuItemActionPerformed(null);
                }
            }
        });
    }

}
